package org.apache.dolphinscheduler.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.dolphinscheduler.api.service.CouponbillService;
import org.apache.dolphinscheduler.api.service.UsersService;
import org.apache.dolphinscheduler.dao.entity.Coupondetail;
import org.apache.dolphinscheduler.dao.mapper.CoupondetailMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PeriodicTaskImpl {
    @Autowired
    private CoupondetailMapper coupondetailMapper;
   @Autowired
    private CouponbillService couponbillService;
    @Scheduled(cron = "0 * * * * ?")
    public void scanDatabaseTable() {
        // 数据库扫描逻辑
        //System.out.println("定时任务执行了");
        Date currentDate = new Date();
        LambdaQueryWrapper<Coupondetail> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Coupondetail::getType, 3);
        List<Coupondetail> couponLists =  coupondetailMapper.selectList(lqw);
        for(Coupondetail couponList : couponLists){
            Date sendStartTime = couponList.getSendStartTime();
            Integer useTimeType = couponList.getUseTimeType();
            Integer issueState = couponList.getIssueState();
            int comparison = currentDate.compareTo(sendStartTime);
            if(comparison >= 0){
                LambdaQueryWrapper<Coupondetail> lqw1 = new LambdaQueryWrapper<>();
                lqw1.eq(Coupondetail::getId, couponList.getId());
                Coupondetail coupondetail =new Coupondetail();
                coupondetail.setType(6);
                coupondetailMapper.update(coupondetail,lqw1);
                if(useTimeType == 1){
                    Integer sendNum = couponbillService.addCouponBillByTimeTask(couponList.getId());
                    coupondetail.setSendNum(sendNum);
                    coupondetailMapper.update(coupondetail,lqw1);
                }
            }
        }
    }
}
